var mongodb = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var BSON = require('mongodb').pure().BSON;
var ObjectID = require("mongodb").ObjectID;

var mongourl = process.env.MONGOLAB_DB ? process.env.MONGOLAB_DB :'mongodb://admin:mta2013@ds039078.mongolab.com:39078/activiteam';//generate_mongo_url(mongo);

exports.createTeam = function(req, res) {

	console.log("createTeame start");
	var doc = req.body;

	var newTeam = {
		name : doc.name,
		sportsField : doc.sportsField,
		skillLevel : doc.skillLevel,
		mainLocation : doc.mainLocation,
		createdBy : doc.createdBy,
		admins : [ doc.createdBy ],
		members : [ doc.createdBy ]
	};

	console.log(req.body);

	var db;
	mongodb.connect(mongourl, function(err, conn) {
		if (err) {
			res.send({
				"EROOR" : "Connection to DB:" + err.message
			});
			console.log("EROOR Connection to DB:" + err.message);
		} else {
			console.log("SUCCESS Connection to DB");
			db = conn;
			db.collection("teams", function(err, collection) {
				if (err) {
					res.send({
						"EROOR" : "Connection to teams documents:"
								+ err.message
					});
					console.log("EROOR Connection to teams documents:"
							+ err.message);
				} else {
					console.log("SUCCESS Connection to teams documents");
					collection.insert(newTeam, function(err, result) {
						if (err) {
							res.send({
								"EROOR" : "create team" + err.message
							});
							console.log("EROOR create team" + err.message);
							return;
						} else {
							res.send({
								"SUCCESS" : "created new Team",
								"_id" : result[0]._id
							});
							console.log("SUCCESS created new team id: "
									+ result[0]._id);

							return;
						}
					});
				}
			});
		}
	});
};

// // Update team
exports.updateTeam = function(req, res) {

	console.log("updateTeam start");
	var doc = req.body;

	var updeTeamData = {
		_id : doc.id,
		name : doc.name,
		sportsField : doc.sportsField,
		skillLevel : doc.skillLevel,
		mainLocation : doc.mainLocation
	};

	var db;
	mongodb.connect(mongourl, function(err, conn) {
		if (err) {
			res.send({
				"EROOR Connection to DB" : err.message
			});
			console.log("EROOR Connection to DB:" + err.message);
		} else {
			console.log("SUCCESS Connection to DB");
			db = conn;
			db.collection("teams", function(err, collection) {
				if (err) {
					console.log("EROOR Connection to teams DB:" + err.message);
					res.send({
						"EROOR Connection to teams DB" : err.message
					});
				} else {
					console.log("SUCCESS Connection to teams documents");

					collection.findOne({
						"_id" : ObjectID(req.params.teamid)
					}, function(err, team) {
						if (err) {
							db.close();
							console.log("db close");
							res.send({
								"EROOR" : "update team" + err.message
							});
						} else if (!team) {
							db.close();
							console.log("db close");
							res.send({
								"EROOR" : "team not exists"
							});
						} else {
							collection.update({
								"_id" : ObjectID(req.params.teamid)
							}, {
								$set : {
									"name" : updeTeamData.name,
									"sportsField" : updeTeamData.sportsField,
									"skillLevel" : updeTeamData.skillLevel,
									"mainLocation" : updeTeamData.mainLocation
								}
							}, {
								safe : true
							}, function(err, team) {

								if (err) {
									res.send({
										"EROOR" : "update team" + err.message
									});
									console.log("EROOR update team"
											+ err.message);
									return;
								} else {
									res.send({
										"SUCCESS" : "update team"
									});
									console.log("SUCCESS update team");
									return;
								}
							});
						}
					});
				}
			});
		}
	});
};

exports.deleteTeam = function(req, res) {

	console.log("deleteTeam start with ID : " + req.params.teamid);

	var db;
	mongodb.connect(mongourl, function(err, conn) {
		if (err) {
			res.send({
				"EROOR Connection to DB" : err.message
			});
			console.log("EROOR Connection to DB:" + err.message);
		} else {
			console.log("SUCCESS Connection to DB");
			db = conn;
			db.collection("teams", function(err, collection) {
				if (err) {
					console.log("EROOR Connection to teams DB:" + err.message);
					res.send({
						"EROOR Connection to teams DB" : err.message
					});
					db.close();
					console.log("close DB");
				} else {
					console.log("SUCCESS Connection to teams documents");

					collection.remove({
						"_id" : ObjectID(req.params.teamid)
					}, 1, function(err, user) {
						if (err) {
							res.send({
								"EROOR" : "delete team" + err.message
							});
							console.log("EROOR delete team" + err.message);
						} else {
							res.send({
								"SUCCESS" : "delete team"
							});
							console.log("SUCCESS delete team");
						}
						db.close();
						console.log("close DB");
					});
				}
			});
		}
	});
};

exports.getTeam = function(req, res) {

	console.log("getTeam start wit ID : " + req.params.teamid);

	var db;
	mongodb.connect(mongourl, function(err, conn) {
		if (err) {
			res.send({
				"EROOR Connection to DB" : err.message
			});
			console.log("EROOR Connection to DB:" + err.message);
		} else {
			console.log("SUCCESS Connection to DB");
			db = conn;
			db.collection("teams", function(err, collection) {
				if (err) {
					console.log("EROOR Connection to teams DB:" + err.message);
					res.send({
						"EROOR Connection to teams DB" : err.message
					});
					db.close();
					console.log("close DB");
				} else {
					console.log("SUCCESS Connection to teams documents");

					collection.findOne({
						"_id" : ObjectID(req.params.teamid)
					}, function(err, team) {
						if (err) {
							res.send({
								"EROOR" : "get team" + err.message
							});
							console.log("EROOR get team" + err.message);
						} else if (!team) {
							res.send({
								"EROOR" : "team is not found"
							});
						} else {
							res.send({
								"SUCCESS" : team
							});
							console.log("SUCCESS get team");
						}
						db.close();
						console.log("close DB");
					});
				}
			});
		}
	});
};

// TODO change the name to AddTeamMember
exports.addTeamMember = function(req, res) {

	console.log("createTeamMember start");

	var doc = req.body;

	var newMemberTeam = {
		nickname : doc.nickname
	};

	var db;
	mongodb.connect(mongourl, function(err, conn) {
		if (err) {
			res.send({
				"EROOR Connection to DB" : err.message
			});
			console.log("EROOR Connection to DB:" + err.message);
		} else {
			console.log("SUCCESS Connection to DB");
			db = conn;
			db.collection("teams", function(err, collection) {
				if (err) {
					console.log("EROOR Connection to teams DB:" + err.message);
					res.send({
						"EROOR Connection to teams DB" : err.message
					});
					db.close();
					console.log("close DB");
				} else {
					console.log("SUCCESS Connection to teams documents");

					collection.findOne({
						"_id" : ObjectID(req.params.teamid)
					}, function(err, team) {
						if (err) {
							res.send({
								"EROOR" : "get team" + err.message
							});
							console.log("EROOR get team" + err.message);
						} else if (!team) {
							res.send({
								"EROOR" : "team is not found"
							});
						} else {
							console.log("SUCCESS get team");
							collection.update({
								"_id" : ObjectID(req.params.teamid)
							}, {
								$addToSet : {
									"members" : newMemberTeam.nickname
								}
							}, {
								safe : true
							}, function(err, user) {
								if (err) {
									res.send({
										"ERROR" : "add member to team"
									});
									return;
								} else {
									res.send({
										"SUCCESS" : "add member to team"
									});
									console.log("SUCCESS add member to team");
									return;
								}
								db.close();
								console.log("close DB");
							});
						}
					});
				}
			});
		}
	});
};
// TODO change the name to getTeamMembers
exports.readTeamMembers = function(req, res) {

	console.log("createTeamMember start");

	var db;
	mongodb.connect(mongourl, function(err, conn) {
		if (err) {
			res.send({
				"EROOR Connection to DB" : err.message
			});
			console.log("EROOR Connection to DB:" + err.message);
		} else {
			console.log("SUCCESS Connection to DB");
			db = conn;
			db.collection("teams", function(err, collection) {
				if (err) {
					console.log("EROOR Connection to teams DB:" + err.message);
					res.send({
						"EROOR Connection to teams DB" : err.message
					});
					db.close();
					console.log("close DB");
				} else {
					console.log("SUCCESS Connection to teams documents");

					collection.findOne({
						"_id" : ObjectID(req.params.teamid)
					}, function(err, team) {

						db.close();
						console.log("close DB");
						if (err) {
							res.send({
								"EROOR" : "get team" + err.message
							});
							console.log("EROOR get team" + err.message);
						} else if (!team) {
							res.send({
								"EROOR" : "team is not found"
							});
						} else {
							console.log("SUCCESS get team");

							res.send({
								"SUCCESS" : team.members
							});
						}
					});
				}
			});
		}
	});
};

exports.deleteTeamMember = function(req, res) {

	console.log("deleteTeamMember start");

	var db;
	mongodb.connect(mongourl, function(err, conn) {
		if (err) {
			res.send({
				"EROOR Connection to DB" : err.message
			});
			console.log("EROOR Connection to DB:" + err.message);
		} else {
			console.log("SUCCESS Connection to DB");
			db = conn;
			db.collection("teams", function(err, collection) {
				if (err) {
					console.log("EROOR Connection to teams DB:" + err.message);
					res.send({
						"EROOR Connection to teams DB" : err.message
					});
					db.close();
					console.log("close DB");
				} else {
					console.log("SUCCESS Connection to teams documents");

					collection.findOne({
						"_id" : ObjectID(req.params.teamid)
					}, function(err, team) {
						if (err) {
							res.send({
								"EROOR" : "get team" + err.message
							});
							console.log("EROOR get team" + err.message);
						} else if (!team) {
							res.send({
								"EROOR" : "team is not found"
							});
						} else {
							console.log("SUCCESS get team");
                                collection.update({
                                    "_id" : ObjectID(req.params.teamid)
                                    },
                                        {$pull:{"members":req.params.memberNickName}},1, function(err,user){
                                            db.close();
                                            if(err){
                                                res.send({
                                                    "ERROR" : "delete member from team"
                                                });
                                            console.log("ERROR delete member from team");
                                            } else {
                                            res.send({
                                                "SUCCESS" : "delete member from team"
                                                });
                                                console.log("SUCCESS delete member from team");
                                            }
                                     });
						}
					});
				}
			});
		}
	});
};


//returns array of events on success, error of failure
exports.getTeamsNearLocation = function(req, res) {
    var _db = null;
    function onMongoConnect(err, db) {
		if(err) {
			console.warn(err);
			res.json({ 'error' : err });
		}
		else {
			_db = db;
			
			var limit =  req.query.limit ? parseInt(req.query.limit) : 100;
			db.executeDbCommand({ 'geoNear' : 'teams' ,
				'near' : [ parseFloat(req.query.longitude) , parseFloat(req.query.latitude) ],
				'maxDistance' : parseFloat(req.query.maxDistance), 'limit' : limit } , onGeoNearComplete);
		}
	}
	
	function onGeoNearComplete(err, geoNearResult) {
		var resJson = null;
		
		if (err) {
			console.warn(err);
			resJson = { 'error' : err };
		}
		else {
			var nearestEvents = [];
			for (var i = 0; i < geoNearResult.documents[0].results.length; i++){
				nearestEvents.push( { 'distance' : geoNearResult.documents[0].results[i].dis,
					'_id' : geoNearResult.documents[0].results[i].obj._id,
					'name' : geoNearResult.documents[0].results[i].obj.name,
					'mainLocation' : geoNearResult.documents[0].results[i].obj.mainLocation
				});
			}
			
			resJson = { 'teams' : nearestEvents };
		}
		
		_db.close();
		
		res.json(resJson);
	}
	
	function isQueryStringValid(queryString) {
		var isValid = false;
		if (typeof(queryString.longitude) != 'undefined' &&
			typeof(queryString.latitude) != 'undefined' &&
			typeof(queryString.maxDistance) != 'undefined') {
			isValid = true;			
		}
		
		return isValid;
	}
	
	if (isQueryStringValid(req.query)) {
		MongoClient.connect(mongourl, onMongoConnect);
	}
	else {
		res.json({ 'error' : 'must contain "longitude", "latitude" and "maxDistance" in query string.'});
	}
};